import re

from flask import Blueprint, request, jsonify, render_template
import pandas as pd
import requests
import json
import requests
import threading
import openpyxl
from openpyxl import Workbook

from methods.pctpOs import upload_image, get_pub_id_by_pub_name
from utils.pctpEnum import pctp_binding, pctp_marketing
from utils.tools import compare_labels

bp = Blueprint("pctpOs", __name__, url_prefix="/pctpOs")


@bp.route('/test', methods=['get'])
def test():
    return "test"


@bp.route('/loginPage', methods=['get'])
def loginPage():
    return render_template('pctp.html')


# 登录api
@bp.route('/loginApi', methods=['post'])
def loginApi():
    j_username = request.form.get('j_username')
    j_password = request.form.get('j_password')
    checkCode = request.form.get('checkCode')
    response = requests.post(
        'https://www.cnpdx.com/service/user/login.do',
        headers={
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
        },
        data={
            'url': '',
            'j_username': j_username,
            'j_password': j_password,
            'checkCode': checkCode,
        },
        verify=False,
    )
    response_json = json.loads(response.text)
    if response_json['status'] == "200":
        phpsessid = re.search(r'YH_TICKET=([^;]+)', response.headers.get('Set-Cookie')).group(1)
        return {'redirectUrl': response_json['redirectUrl'], 'status': response_json['status'], 'phpsessid': phpsessid}
    else:
        return response_json


# 检测登录状态是否过期
@bp.route('/checkSession', methods=['get'])
def checkSession():
    phpsessid = request.args.get('phpsessid')
    if not phpsessid:
        return "请传入phpsessid"
    cookies = {
        'YH_TICKET': phpsessid,
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    }
    params = {
        'soId': '1627',
    }
    response = requests.get('https://yicaigou.cnpdx.com/pr/mymodule', params=params, cookies=cookies, headers=headers)
    if re.compile(r'<\s*html', re.I).search(response.text) is not None:
        return {'code': 0, 'message': '出版物协同交易平台登录状态已过期'}
    # 解析为json格式
    response_json = json.loads(response.text)
    if not response_json['success']:
        return {'code': 0, 'message': '出版物协同交易平台登录状态已过期'}
    else:
        return {'code': 200, 'message': '出版物协同交易平台登录状态未过期'}


# 出版物协同交易平台发布
@bp.route('/publishProduct', methods=['post'])
def publishProduct():
    data = request.get_json()
    dcc_token = data.get('dcc_token')
    serial_no = data.get('serial_no')
    phpsessid = data.get('phpsessid')
    if dcc_token is None:
        return {'code': 0, 'message': '请传入dcc_token'}
    if serial_no is None:
        return {'code': 0, 'message': '请传入serial_no'}
    if phpsessid is None:
        return {'code': 0, 'message': '请传入phpsessid'}
    book_details = requests.get(
        f'http://open.cloudycentury.net:6600/prod-api/bookinfo/infoBase/query/{serial_no}',
        headers={
            'Authorization': f'Bearer {dcc_token}',
        },
        verify=False,
    )
    book_details_json = json.loads(book_details.text)
    if book_details_json['code'] != 200:
        return {'code': 0, 'message': book_details_json['message']}
    book_details_json = book_details_json['data']
    # 准备上传图片
    pic_id = []
    # 创建一个线程列表
    threads = []
    def upload_worker(image_url, yh_ticket, photo_code, index, pic_id):
        upload_image_json = upload_image(image_url, yh_ticket, photo_code, index)
        if upload_image_json['success']:
            pic_id.append(str(upload_image_json['obj']['id']))

    book_info_file_obj_list = book_details_json['bookInfoFileObjList']
    if not book_info_file_obj_list or len(book_info_file_obj_list) != 0:
        img_index = 0
        # 上传平面封
        pmf_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "2"][:2]
        if pmf_dcc_urls:
            for item in pmf_dcc_urls:
                thread = threading.Thread(target=upload_worker,
                                          args=(item['webUrl'], phpsessid, 'COVERIMG', img_index, pic_id))
                threads.append(thread)
                # upload_image_json = upload_image(item['webUrl'], phpsessid, 'COVERIMG', img_index)
                # if upload_image_json['success']:
                #     pic_id.append(str(upload_image_json['obj']['id']))
                img_index += 1
        # 授权文件暂时不传
        # 立体封面
        ltf_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "1"][:2]
        if ltf_dcc_urls:
            for item in ltf_dcc_urls:
                # upload_image_json = upload_image(item['webUrl'], phpsessid, 'SOLID', img_index)
                # if upload_image_json['success']:
                #     pic_id.append(str(upload_image_json['obj']['id']))
                thread = threading.Thread(target=upload_worker,
                                          args=(item['webUrl'], phpsessid, 'SOLID', img_index, pic_id))
                threads.append(thread)
                img_index += 1
        # 条码图
        tm_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "6"][:2]
        if tm_dcc_urls:
            for item in tm_dcc_urls:
                # upload_image_json = upload_image(item['webUrl'], phpsessid, 'BARCODEIMG', img_index)
                # if upload_image_json['success']:
                #     pic_id.append(str(upload_image_json['obj']['id']))
                thread = threading.Thread(target=upload_worker,
                                          args=(item['webUrl'], phpsessid, 'BARCODEIMG', img_index, pic_id))
                threads.append(thread)
                img_index += 1
        # 版权页
        bqy_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "4"][:2]
        if bqy_dcc_urls:
            for item in bqy_dcc_urls:
                # upload_image_json = upload_image(item['webUrl'], phpsessid, 'COLOPHONIMG', img_index)
                # if upload_image_json['success']:
                #     pic_id.append(str(upload_image_json['obj']['id']))
                thread = threading.Thread(target=upload_worker,
                                          args=(item['webUrl'], phpsessid, 'COLOPHONIMG', img_index, pic_id))
                threads.append(thread)
                img_index += 1
        # 详情页
        xqy_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "17"][:2]
        if xqy_dcc_urls:
            for item in xqy_dcc_urls:
                # upload_image_json = upload_image(item['webUrl'], phpsessid, 'PRODUCT_DETAIL', img_index)
                # if upload_image_json['success']:
                #     pic_id.append(str(upload_image_json['obj']['id']))
                thread = threading.Thread(target=upload_worker,
                                          args=(item['webUrl'], phpsessid, 'PRODUCT_DETAIL', img_index, pic_id))
                threads.append(thread)
                img_index += 1
        # 实拍图
        spt_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "19"][:2]
        if spt_dcc_urls:
            for item in spt_dcc_urls:
                # upload_image_json = upload_image(item['webUrl'], phpsessid, 'REAL_SCENE', img_index)
                # if upload_image_json['success']:
                #     pic_id.append(str(upload_image_json['obj']['id']))
                thread = threading.Thread(target=upload_worker,
                                          args=(item['webUrl'], phpsessid, 'REAL_SCENE', img_index, pic_id))
                threads.append(thread)
                img_index += 1
        # 立体透明图
        tmt_dcc_urls = [item for item in book_info_file_obj_list if item["fileType"] == "9"][:2]
        if tmt_dcc_urls:
            for item in tmt_dcc_urls:
                # upload_image_json = upload_image(item['webUrl'], phpsessid, 'SOLID_TRANSPARENT', img_index)
                # if upload_image_json['success']:
                #     pic_id.append(str(upload_image_json['obj']['id']))
                thread = threading.Thread(target=upload_worker,
                                          args=(item['webUrl'], phpsessid, 'SOLID_TRANSPARENT', img_index, pic_id))
                threads.append(thread)
                img_index += 1
    # 启动所有线程
    for thread in threads:
        thread.start()

    # 等待所有线程完成
    for thread in threads:
        thread.join()

    print(pic_id)  # 打印所有上传成功的图片ID
    paper_back = compare_labels(book_details_json['binding'], pctp_binding)
    if paper_back is None:
        return {'code': 0, 'message': '没有找到合适的纸张类型'}
    publisher_code = get_pub_id_by_pub_name(book_details_json['publishName'], phpsessid)
    if publisher_code is None:
        return {'code': 0, 'message': '没有找到合适的出版社'}
    if book_details_json['publishDate'] == '' or book_details_json['publishDate'] is None:
        return {'code': 0, 'message': '请传入出版年月'}
    if book_details_json['versionNo'] == '' or book_details_json['versionNo'] is None:
        return {'code': 0, 'message': '请传入版次'}
    marketing_categories = compare_labels(book_details_json['marketingCategoryName'], pctp_marketing)
    if marketing_categories is None:
        return {'code': 0, 'message': '没有找到合适的营销类别'}
    data = {
        'infoSoure': 'LR',
        'keyId': '',
        'roleKey': 'PQ',
        'issuitbookPur': '0002200666',
        'picId': ', '.join(pic_id),  # 图片id
        'isOverOnlyBook': '0',  # 一号多书 --必填（有默认值默认0、否）
        'isImportant': '0',  # 是否重点 --必填（有默认值默认0、否）
        'isbn': book_details_json['isbn'] or '',  # isbn 必填
        'price': book_details_json['priceFixed'] or '',  # 价格 必填
        'bookTitle': book_details_json['bookName'] or '',  # 书名 必填
        'affiliateSeries': book_details_json['seriesTitleName'] or '',  # 丛书名 丛书必填
        'isSuitBook': '0',  # 出版标识 --必填（有默认值默认0、单品）
        'bookletNum': '',  # 套装册数(套书必填)
        'authorEditor': book_details_json['authorName'] or '',  # 著者  --必填
        'editor': book_details_json['editorResponsible'] or '',  # 编者
        'translator': book_details_json['translatorName'] or '',  # 译者
        'drawing': '',  # 绘者
        'classification': book_details_json['bookInfoAppendObj']['classificationNumber'] or '',  # 中图法分类号 --必填
        'emendation': '',  # 其他作者
        'paperBack': paper_back,  # 装帧 --必填
        'edition': book_details_json['publishName'] or '',  # 出版社 --必填
        'publisherCode': publisher_code,  # 出版社号 --必填
        'editionYearMonth': book_details_json['publishDate'] or '',  # 出版年月 --必填
        'version': book_details_json['versionNo'] or '',  # 版次 --必填
        'marketingCategories': marketing_categories,  # 营销分类
        'firstPulish':  book_details_json['printNumber'] or '',  # 首印数 --必填
        'audience': book_details_json['bookInfoAppendObj']['readerObject'] or '',  # 读者对象
        'recommendSaleGroup': '',  # 上架建议
        'isAdvance': '0',  # 建议预售 默认0否
        'arrivedAdvanceTime': '',  # 预售发货日期
        'length': book_details_json['bookInfoAppendObj']['lengthBook'] or '',  # 长(mm)
        'wide': book_details_json['bookInfoAppendObj']['widthBook'] or '',  # 宽(mm)
        'high': book_details_json['bookInfoAppendObj']['depthBook'] or '',  # 高(mm)
        'weight': book_details_json['bookInfoAppendObj']['weight'] or '',  # 重量(g)
        'bagPerNum': book_details_json['packetNumber'] or '',  # 自然包册数
        'supplierCommoditiesId': '',  # 供应商商品ID
        # 交易信息 暂时不用填写
        'markeInfos[0].purchaserId': '0002200666',
        'markeInfos[0].owner': '',
        'markeInfos[0].purchaserName': '四川文轩在线电子商务有限公司',
        'markeInfos[0].discountRate': '',
        'markeInfos[0].shopRecommendSubscriptions': '',
        'markeInfos[0].recommendSubscriptions': '',
        'markeInfos[1].purchaserId': '0004100001',
        'markeInfos[1].owner': '',
        'markeInfos[1].purchaserName': '深圳书城新华书业连锁总部有限公司',
        'markeInfos[1].discountRate': '',
        'markeInfos[1].recommendSubscriptions': '',
        'markeInfos[1].mcassort': '',
        'markeInfos[2].purchaserId': '0002300044',
        'markeInfos[2].owner': '',
        'markeInfos[2].purchaserName': '广东新华发行集团',
        'markeInfos[2].discountRate': '',
        'markeInfos[2].recommendSubscriptions': '',
        'copyrightPageBooktitle': '',  # 版权页书名
        'format': book_details_json['bookSize'] or '',  # 开本
        'enbookName': book_details_json['originalBookName'] or '',  # 外文书名
        'ageGroup': '',  # 年龄段(少儿必填)
        'cipNum': '',  # CIP数据核字
        'schoolAgeGroup': '',  # 学龄段(文教必填)
        'pageNumber': book_details_json['pagesNumber'] or '',  # 页码
        'wordNumber': book_details_json['fontNumber'] or '',  # 字数 示例：175千字或 175000
        'sheet': book_details_json['printPage'] or '',  # 印张
        'bodyLanguage': book_details_json['textLanguage'] or '',  # 正文语种
        'paper': '',  # 用纸
        'keyWord': '',  # 主题词
        'printYearMonth': '',  # 本次印刷年月
        'impression': '',  # 印次
        'publisherAssigneeCountry': '中国大陆',  # 出版者国别 默认中国大陆
        'placePublished': '',  # 出版地
        'typeAndQuantity': '',  # 附件信息
        'firstEditionYearMonth': '',  # 首版年月
        'clobDataInfoPmsDos[0].clobType': 'SUMMARY',  # 内容简介
        'clobDataInfoPmsDos[0].clobInfo': book_details_json['bookInfoAdditionObj']['briefIntroduction'] or '',
        'clobDataInfoPmsDos[8].clobType': 'BOOKAUTHOR',
        'clobDataInfoPmsDos[8].clobInfo': book_details_json['bookInfoAdditionObj']['authorAbout'] or '',
        'clobDataInfoPmsDos[1].clobType': 'DIRECTORY',  # 目录
        'clobDataInfoPmsDos[1].clobInfo': book_details_json['bookInfoAdditionObj']['tableOfContents'] or '',
        'clobDataInfoPmsDos[4].clobType': 'PREFACE',
        'clobDataInfoPmsDos[4].clobInfo': book_details_json['bookInfoAdditionObj']['preface'] or '',
        'clobDataInfoPmsDos[6].clobType': 'DELICACYCONTENTS',
        'clobDataInfoPmsDos[6].clobInfo': book_details_json['bookInfoAdditionObj']['onlineReading'] or '',
        'clobDataInfoPmsDos[3].clobType': 'EDITORRECOMMEND',
        'clobDataInfoPmsDos[3].clobInfo': book_details_json['bookInfoAdditionObj']['editRecommend'] or '',
        'clobDataInfoPmsDos[5].clobType': 'CELEBRITYENDORSEMENTS',
        'clobDataInfoPmsDos[5].clobInfo': '',
        'clobDataInfoPmsDos[7].clobType': 'MEDIUMCRITICISM',
        'clobDataInfoPmsDos[7].clobInfo': book_details_json['bookInfoAdditionObj']['mediaReview'] or '',
        'clobDataInfoPmsDos[9].clobType': 'AWARDS',
        'clobDataInfoPmsDos[9].clobInfo': '',
        'clobDataInfoPmsDos[2].clobType': 'SELLINGPOINT',
        'clobDataInfoPmsDos[2].clobInfo': '',
    }
    final_response = requests.post('https://fx.cnpdx.com/pms/pms/masterdata/json/saveMasterdata', cookies={
        'YH_TICKET': phpsessid,
    }, headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    }, data=data)
    print(final_response.text)
    final_response_json = json.loads(final_response.text)
    if final_response_json['success']:
        return {'code': 200, 'message': '上架成功'}
    else:
        return {'code': 0, 'message': final_response_json['msg']}
